import axios from "../../http/axios.js";
import {
  apiUpdate_userPhone,
  apiGetUserInfo
} from "../../http/server.js";
import {
  regExpPhone
} from "../../utils/regular.js";

Page({
  data: {
    titleOne: {
      key: "更改手机号码",
      value: "请输入新的手机号码"
    },
    titleTwo: {
      key: "+86",
      value: "13935311111"
    }
  },

  onLoad: function(options) {
    this.setUserInfo();
  },

  onReady: function() {

  },

  onShow: function() {

  },
  setUserInfo: function() {
    let userInfo = wx.getStorageSync("userInfo");
    let titleTwo = {
      ...this.data.titleTwo,
      value: userInfo.phone
    }
    this.setData({
      titleTwo
    })
  },
  // 修改密码
  updateInputValue: function(e) {
    let titleTwo = this.data.titleTwo;
    titleTwo.value = e.detail;
    this.setData({
      titleTwo
    })
  },
  // 进行手机号验证
  testPhone: function() {
    let phone = this.data.titleTwo.value;
    if (!phone.length) {
      wx.showToast({
        title: "请输入手机号",
        icon: "none"
      });
      return false;
    }
    if (!regExpPhone.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none"
      });
      return false;
    }
    return true;
  },
  // 点击完成
  handleClickSuccess: function() {
    if (!this.testPhone()) {
      return;
    }
    let userInfo = wx.getStorageSync("userInfo");
    let data = {
      userId: userInfo.userId,
      phone: this.data.titleTwo.value
    }
    axios({
        url: apiUpdate_userPhone,
        method: "POST",
        data: data
      })
      .then(res => {
        axios({
          url: apiGetUserInfo,
          data: {
            userId: userInfo.userId
          }
        }).then(res => {
          wx.setStorageSync("userInfo", { ...res,
            userType: userInfo.userType
          });
          wx.showToast({
            title: "手机号修改成功",
            icon: "none"
          });
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        })
      })
  }
})